package com.lr.controller;

import com.lr.PO.TbProduct;
import com.lr.VO.JsonResultVo;
import com.lr.VO.Product;
import com.lr.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Controller
public class DianZanController {
    @Resource
    private IProductService iProductService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @RequestMapping("/toIndex.do")
    public String toindex(Model model){
        //查询商品列表
        List<TbProduct> tbProducts = iProductService.selectProductList();
        List<Product> products = new ArrayList<>();
        if (null != tbProducts){
            for (TbProduct tp:tbProducts
                 ) {
                Product product = new Product();
                product.setProductId(tp.getProductId());
                product.setProductName(tp.getProductName());
                product.setProductMinPrice(tp.getProductMinPrice());
                /*判断redis中对应商品是否存在key*/
                Boolean aBoolean = stringRedisTemplate.hasKey("zan-1-" + tp.getProductId());

                product.setZan(aBoolean);
                products.add(product);
            }
        }
        model.addAttribute("products",products);
        return "index";
    }

    @RequestMapping("/dianzan.do")
    @ResponseBody
    public JsonResultVo dianzan(String key,String flag){

        JsonResultVo jsonResultVo = new JsonResultVo();

        //key包含操作zan,用户1,产品id xxx
        if (flag.contains("empty")){
            /*从有赞变无*/
            stringRedisTemplate.delete(key);
            jsonResultVo.setCode(0);
            jsonResultVo.setMsg("fail");
        }else {
            /*设置赞,存在redis*/
            stringRedisTemplate.boundValueOps(key).set("zan");
            jsonResultVo.setCode(1);
            jsonResultVo.setMsg("success");
        }


        return jsonResultVo;
    }
}
